#include "flip_internal.hpp"

#include <flip/gl/button_names.hpp>

static luaL_Reg flip[] =
{
	LUAN(video),
	LUAN(update),
	LUAN(end_drawing),
	LUAN(next_event),
	LUAN(throttle_fps),
	LUAN(begin_quads), LUAN(quad),
	LUAN(begin_sprites), LUAN(sprite),
	LUAN(sprite_centered),
	LUAN(sprite_centered_rot),
	LUAN(text),
	LUAN(clear),
	LUAN(color),
	LUAN(clear),
	LUAN(create_image),
	LUAN(load_image),
	LUAN(load_font),
	LUAN(draw_sprite),
	LUAN(close),

	LUAN(lua_test_flush_buffers), // Test
	{NULL, NULL}
};

static luaL_Reg flip_image[] =
{
	LUAN(to_sprite),
	LUAN(setpixel),
	LUAN2(dim, image_dim),

	{"__gc", luaflip_image_gc},
	{0, 0}
};

static luaL_Reg flip_sprite[] =
{
	{"__gc", luaflip_sprite_gc},
	{0, 0}
};

static luaL_Reg flip_core_font[] =
{
	{"__gc", luaflip_font_gc},
	{0, 0}
};

luaflipData globalDataInstance;

int luaopen_flip(lua_State* L)
{
#if 0
	void* rawData = (luaflipData*)lua_newuserdata(L, sizeof(luaflipData));
	new(rawData) luaflipData;
#else
	lua_pushinteger(L, 0);
#endif

	lua_pushvalue(L, -1); // data data
	make_metatable(L, &flip_image_tag, flip_image, 1); // data | mt
	lua_pushvalue(L, -1); // ... | mt mt
	lua_setfield(L, -2, "__index"); // ... | mt
	lua_pop(L, 1); // data

	lua_pushvalue(L, -1); // data data
	make_metatable(L, &flip_sprite_tag, flip_sprite, 1); // data | mt
	lua_pushvalue(L, -1); // ... | mt mt
	lua_setfield(L, -2, "__index"); // ... | mt
	lua_pop(L, 1); // data
	
	lua_pushvalue(L, -1); // data data
	luaL_openlib(L, "flip", flip, 1); // data flip

	for(int i = 0; Flip::buttonNames[i].name; ++i)
	{
		lua_pushinteger(L, Flip::buttonNames[i].button);
		lua_setfield(L, -2, Flip::buttonNames[i].name);
	}

	return 1;
}
